//
//  YDContact.m
//  IngCard
//
//  Created by kf on 2017/5/17.
//  Copyright © 2017年 IngDan. All rights reserved.
//

#import "YDContact.h"

NS_ASSUME_NONNULL_BEGIN

@interface YDContact ()

@property(nonatomic, assign) ABRecordRef recordRef;

@end

@implementation YDContact

+ (YDContact *) contactWithRecordRef:(ABRecordRef) recordRef
{
    //初始化一个YContactObject对象
    YDContact * contact = [[YDContact alloc]init];
    
    recordRef = recordRef;
    //类型
    contact.type = [YDContact contactType:recordRef];
    
    //头像
    contact.headImage = [YDContact contactHeadImage:recordRef];

    //备注
    contact.note = (__bridge NSString *)(ABRecordCopyValue(recordRef, kABPersonNoteProperty));
    
    //创建时间
    contact.creationDate = (__bridge NSDate *)(ABRecordCopyValue(recordRef, kABPersonCreationDateProperty));
    
    //最近一次修改的时间
    contact.modificationDate = (__bridge NSDate *)(ABRecordCopyValue(recordRef, kABPersonModificationDateProperty)); //最近一次修改的时间
    
    //姓名对象
    contact.name = [YDContactNameInfo contactName:recordRef];
    
    //电话对象
    contact.phone = [YDContactPhoneInfo contactPhones:recordRef];
    
    //工作对象
    contact.job = [YDContactJobInfo contactJob:recordRef];
    
    //邮件对象
    contact.emailAddresses = [YDContactEmailInfo contactEmail:recordRef];
    
    //地址对象
    contact.addresses = [YDContactAddressInfo contactAddress:recordRef];
    
    //生日对象
    contact.brithday = [YDContactBrithdayInfo contactBrithday:recordRef];
    
    //即时通信对象
    contact.instantMessage = [YDContactInstantMessageInfo contactInstantMessage:recordRef];
    
    //关联对象
    contact.relatedNames = [YDContactRelatedNamesInfo contactRelatedNames:recordRef];
    
    //社交简介
    contact.socialProfiles = [YDContactSocialProfileInfo contactSocialProfiles:recordRef];
    
    return contact;
}


- (NSString *)fullName
{
    if (!_fullName)
    {
        self.name.middleName = (self.name.middleName) ? self.name.middleName : @"";
        self.name.givenName = (self.name.givenName) ? self.name.givenName : @"";
        self.name.familyName = (self.name.familyName) ? self.name.familyName : @"";
        
        _fullName = [[self.name.familyName stringByAppendingString:self.name.middleName] stringByAppendingString:self.name.givenName];;
    }
    
    return _fullName;
}

#pragma mark - private
+ (YDContactType)contactType:(ABRecordRef) recordRef
{
    //获得类型属性
    CFNumberRef typeIndex = ABRecordCopyValue(recordRef, kABPersonKindProperty);
    
    YDContactType type = YDContactTypePerson;
    //表示是公司联系人
    if (CFNumberCompare(typeIndex, kABPersonKindOrganization, nil) == kCFCompareEqualTo)
    {
        type = YDContactTypeOrigination;
    }
    
    //释放资源
    CFRelease(typeIndex);
    return type;
}

+ (UIImage *)contactHeadImage:(ABRecordRef) recordRef
{
    //首先判断是否存在头像
    if (ABPersonHasImageData(recordRef) == false)//没有头像，返回nil
    {
        return nil;
    }
    
    //开始获得头像信息
    NSData * imageData = (__bridge NSData *)(ABPersonCopyImageData(recordRef));
    
    //获得头像原图
    //NSData * imageData = CFBridgingRelease(ABPersonCopyImageDataWithFormat(self.recordRef, kABPersonImageFormatOriginalSize));
    
    return [UIImage imageWithData:imageData];
}



@end


@implementation YDContactNameInfo


+ (YDContactNameInfo *)contactName:(ABRecordRef) recordRef
{
    
    YDContactNameInfo * nameObject = [[YDContactNameInfo alloc]init];
    
    nameObject.givenName = (__bridge NSString *)(ABRecordCopyValue(recordRef, kABPersonFirstNameProperty));             //名字
    nameObject.phoneticGivenName = (__bridge NSString *)(ABRecordCopyValue(recordRef, kABPersonFirstNamePhoneticProperty));  //名字的拼音音标
    
    nameObject.familyName = (__bridge NSString *)(ABRecordCopyValue(recordRef, kABPersonLastNameProperty));             //姓氏
    nameObject.phoneticFamilyName = (__bridge NSString *)(ABRecordCopyValue(recordRef, kABPersonLastNamePhoneticProperty)); //姓氏的拼音音标
    
    nameObject.middleName = (__bridge NSString *)(ABRecordCopyValue(recordRef, kABPersonMiddleNameProperty));           //名字中的信仰名称
    nameObject.phoneticMiddleName = (__bridge NSString *)(ABRecordCopyValue(recordRef, kABPersonMiddleNamePhoneticProperty)); //英文信仰缩写字母的拼音音标
    nameObject.namePrefix = (__bridge NSString *)(ABRecordCopyValue(recordRef, kABPersonPrefixProperty));            //名字前缀
    nameObject.nameSuffix = (__bridge NSString *)(ABRecordCopyValue(recordRef, kABPersonSuffixProperty));                 //名字后缀
    nameObject.nickName = (__bridge NSString *)(ABRecordCopyValue(recordRef, kABPersonNicknameProperty));            //名字昵称

    return nameObject;
}
@end


@implementation YDContactPhoneInfo


+ (NSArray <YDContactPhoneInfo *> *)contactPhones:(ABRecordRef)recordRef
{
    //外传数组
    NSMutableArray <YDContactPhoneInfo *> * phones = [NSMutableArray arrayWithCapacity:0];
    
    //获得电话号码的多值对象
    ABMultiValueRef values = ABRecordCopyValue(recordRef, kABPersonPhoneProperty);
    
    for (NSInteger i = 0; i < ABMultiValueGetCount(values); i++)
    {
        YDContactPhoneInfo * phoneObject = [[YDContactPhoneInfo alloc]init];
        
        //开始赋值
        phoneObject.phoneTitle = (__bridge NSString *)ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(values, i)); //电话描述(如住宅、工作..)
        phoneObject.phoneNumber = (__bridge NSString *)ABMultiValueCopyValueAtIndex(values, i);                                 //电话号码
        
        //添加数据
        [phones addObject:phoneObject];
    }
    
    //释放资源
    CFRelease(values);
    
    return [NSArray arrayWithArray:phones];
}



@end


@implementation YDContactJobInfo
+ (YDContactJobInfo *)contactJob:(ABRecordRef) recordRef
{
    YDContactJobInfo * jobObject = [[ YDContactJobInfo alloc]init];
    
    jobObject.organizationName = (__bridge NSString *)(ABRecordCopyValue(recordRef, kABPersonOrganizationProperty));//公司
    jobObject.departmentName = (__bridge NSString *)(ABRecordCopyValue(recordRef, kABPersonDepartmentProperty)); //部门
    jobObject.jobTitle = (__bridge NSString *)(ABRecordCopyValue(recordRef, kABPersonJobTitleProperty)); //职务
    return jobObject;
}


@end


@implementation YDContactEmailInfo

+ (NSArray <YDContactEmailInfo *> *)contactEmail:(ABRecordRef) recordRef
{
    //外传数组
    NSMutableArray <YDContactEmailInfo *> * emails = [NSMutableArray arrayWithCapacity:0];
    
    //获取多值属性
    ABMultiValueRef values = ABRecordCopyValue(recordRef, kABPersonEmailProperty);
    
    //遍历添加
    for (NSInteger i = 0; i < ABMultiValueGetCount(values); i++)
    {
        YDContactEmailInfo * emailObject = [[YDContactEmailInfo alloc]init];
        
        emailObject.emailTitle = (__bridge NSString *)(ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(values, i)));  //邮件描述
        emailObject.emailAddress = (__bridge NSString *)(ABMultiValueCopyValueAtIndex(values, i));                                 //邮件地址
        //添加
        [emails addObject:emailObject];
    }
    
    //释放资源
    CFRelease(values);
    
    return [NSArray arrayWithArray:emails];
}

@end


@implementation YDContactAddressInfo

+ (NSArray <YDContactAddressInfo *> *)contactAddress:(ABRecordRef) recordRef
{
    //外传数组
    NSMutableArray <YDContactAddressInfo *> * addresses = [NSMutableArray arrayWithCapacity:0];
    
    //获取多指属性
    ABMultiValueRef values = ABRecordCopyValue(recordRef, kABPersonAddressProperty);
    
    //遍历添加
    for (NSInteger i = 0; i < ABMultiValueGetCount(values); i++)
    {
        YDContactAddressInfo * addressObject = [[YDContactAddressInfo alloc]init];
        
        //赋值
        addressObject.addressTitle = (__bridge NSString *)ABAddressBookCopyLocalizedLabel((ABMultiValueCopyLabelAtIndex(values, i)));                    //地址标签
        
        //获得属性字典
        NSDictionary * dictionary = (__bridge NSDictionary *)ABMultiValueCopyValueAtIndex(values, i);
        
        //开始赋值
        addressObject.country = [dictionary valueForKey:(__bridge NSString *)kABPersonAddressCountryKey];               //国家
        addressObject.city = [dictionary valueForKey:(__bridge NSString *)kABPersonAddressCityKey];                     //城市
        addressObject.state = [dictionary valueForKey:(__bridge NSString *)kABPersonAddressStateKey];                   //省(州)
        addressObject.street = [dictionary valueForKey:(__bridge NSString *)kABPersonAddressStreetKey];                 //街道
        addressObject.postalCode = [dictionary valueForKey:(__bridge NSString *)kABPersonAddressZIPKey];                //邮编
        addressObject.ISOCountryCode = [dictionary valueForKey:(__bridge NSString *)kABPersonAddressCountryCodeKey];    //ISO国家编号
        
        //添加数据
        [addresses addObject:addressObject];
    }
    
    //释放资源
    CFRelease(values);
    
    return [NSArray arrayWithArray:addresses];
    
}
@end



@implementation YDContactBrithdayInfo

+ (YDContactBrithdayInfo *)contactBrithday:(ABRecordRef) recordRef
{
    //实例化对象
    YDContactBrithdayInfo * brithdayObject = [[YDContactBrithdayInfo alloc]init];
    
    //生日的日历
    brithdayObject.brithdayDate = (__bridge NSDate *)(ABRecordCopyValue(recordRef, kABPersonBirthdayProperty));  //生日的时间对象
    
    //获得农历日历属性的字典
    NSDictionary * brithdayDictionary = (__bridge NSDictionary *)(ABRecordCopyValue(recordRef, kABPersonAlternateBirthdayProperty));
    
    //农历日历的属性，设置为农历属性的时候，此字典存在数值
    if (brithdayDictionary != nil)
    {
        
        brithdayObject.calendar = [brithdayDictionary valueForKey:@"calendar"];                                 //农历生日的标志位,比如“chinese”
        
        //农历生日的相关存储属性
        brithdayObject.era = [(NSNumber *)[brithdayDictionary valueForKey:@"era"] integerValue];                //纪元
        brithdayObject.year = [(NSNumber *)[brithdayDictionary valueForKey:@"year"] integerValue];              //年份,六十组干支纪年的索引数，比如12年为壬辰年，为循环的29,此数字为29
        
        brithdayObject.month = [(NSNumber *)[brithdayDictionary valueForKey:@"month"] integerValue];            //月份
        brithdayObject.leapMonth = [(NSNumber *)[brithdayDictionary valueForKey:@"isLeapMonth"] boolValue];     //是否是闰月
        brithdayObject.day = [(NSNumber *)[brithdayDictionary valueForKey:@"day"] integerValue];                //日期
        
    }
    
    //返回对象
    return brithdayObject;
}

@end



@implementation YDContactInstantMessageInfo

+ (NSArray <YDContactInstantMessageInfo *> *)contactInstantMessage:(ABRecordRef) recordRef
{
    //存放数组
    NSMutableArray <YDContactInstantMessageInfo *> * instantMessages = [NSMutableArray arrayWithCapacity:0];
    
    //获取数据字典
    ABMultiValueRef messages = ABRecordCopyValue(recordRef, kABPersonInstantMessageProperty);
    
    //遍历获取值
    for (NSInteger i = 0; i < ABMultiValueGetCount(messages); i++)
    {
        //获取属性字典
        NSDictionary * messageDictionary = CFBridgingRelease(ABMultiValueCopyValueAtIndex(messages, i));
        
        //实例化
        YDContactInstantMessageInfo * instantMessageObject = [[YDContactInstantMessageInfo alloc]init];
        
        instantMessageObject.service = [messageDictionary valueForKey:@"service"];          //服务名称(如QQ)
        instantMessageObject.userName = [messageDictionary valueForKey:@"username"];        //服务账号(如QQ号)
        
        //添加
        [instantMessages addObject:instantMessageObject];
    }
    
    CFRelease(messages);
    return [NSArray arrayWithArray:instantMessages];
}


@end


@implementation YDContactRelatedNamesInfo

+ (NSArray <YDContactRelatedNamesInfo *> *)contactRelatedNames:(ABRecordRef) recordRef
{
    //存放数组
    NSMutableArray <YDContactRelatedNamesInfo *> * relatedNames = [NSMutableArray arrayWithCapacity:0];
    
    //获得多值属性
    ABMultiValueRef names = ABRecordCopyValue(recordRef, kABPersonRelatedNamesProperty);
    
    //遍历赋值
    for (NSInteger i = 0; i < ABMultiValueGetCount(names); i++)
    {
        //初始化
        YDContactRelatedNamesInfo * relatedName = [[YDContactRelatedNamesInfo alloc]init];
        
        //赋值
        relatedName.relatedTitle = CFBridgingRelease(ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(names, i))); //关联的标签(如friend)
        relatedName.relatedName = CFBridgingRelease(ABMultiValueCopyValueAtIndex(names, i));                                    //关联的名称(如联系人姓名)
        
        //添加
        [relatedNames addObject:relatedName];
    }
    
    CFRelease(names);
    return [NSArray arrayWithArray:relatedNames];
}


@end



@implementation YDContactSocialProfileInfo

+ (NSArray <YDContactSocialProfileInfo *> *)contactSocialProfiles:(ABRecordRef) recordRef
{
    //外传数组
    NSMutableArray <YDContactSocialProfileInfo *> * socialProfiles = [NSMutableArray arrayWithCapacity:0];
    
    //获得多值属性
    ABMultiValueRef profiles = ABRecordCopyValue(recordRef, kABPersonSocialProfileProperty);
    
    //遍历取值
    for (NSInteger i = 0; i < ABMultiValueGetCount(profiles); i++)
    {
        //初始化对象
        YDContactSocialProfileInfo * socialProfileObject = [[YDContactSocialProfileInfo alloc]init];
        
        //获取属性值
        NSDictionary * profileDictionary = CFBridgingRelease(ABMultiValueCopyValueAtIndex(profiles, i));
        
        //开始赋值
        socialProfileObject.socialProfileTitle = [profileDictionary valueForKey:@"service"];    //社交简介(如sinaweibo)
        socialProfileObject.socialProFileAccount = [profileDictionary valueForKey:@"username"]; //社交地址(如123456)
        socialProfileObject.socialProFileUrl = [profileDictionary valueForKey:@"url"];          //社交链接的地址(按照上面两项自动为http://weibo.com/n/123456)
        
        //添加
        [socialProfiles addObject:socialProfileObject];
    }
    
    CFRelease(profiles);
    return [NSArray arrayWithArray:socialProfiles];
}


@end





NS_ASSUME_NONNULL_END
